package relaychat.websocket;

import java.util.Set;


import org.eclipse.jetty.websocket.WebSocket.OnTextMessage;

/**
 * ChatWebSocket
 * 
 * This class handles the input and output of the messages send along the web socket.
 * 
 */
public class ChatWebSocket implements OnTextMessage {

	private Connection connection;
	
	private Set<ChatWebSocket> users;

	//empty constructor
	public ChatWebSocket() {

	}

	//construtor with argument for a set of users
	public ChatWebSocket(Set<ChatWebSocket> users ) {
		this.users = users;
	}

	/**
	 * onMessage
	 * param data
	 * Takes message data from one user and sends it out to all connected users
	 */
	public void onMessage(String data) {
		for (ChatWebSocket user : users) {
			try {
				user.connection.sendMessage(data);
			} catch (Exception e) {
				System.out.println("onMessageProblem");
			}
		}

	}

	/**
	 * onOpen
	 * param connection
	 * Adds connection to the list of users when new connection is made
	 */
	@Override
	public void onOpen(Connection connection) {
		this.connection = connection;
		users.add(this);
		
	}

	/**
	 * onClose
	 * params closeCode, message
	 * removes user from the list of user connections
	 */
	@Override
	public void onClose(int closeCode, String message) {
		users.remove(this);
		
	}

}
